package com.bright.hxj.cwduijie.service.impl;

import com.bright.ghj.common.util.ListUtil;
import com.bright.ghj.common.util.StringUtil;
import com.bright.hxj.cwduijie.converter.VoucherConverter;
import com.bright.hxj.cwduijie.enums.DataApi;
import com.bright.hxj.cwduijie.pojo.bo.ApiDataCollection;
import com.bright.hxj.cwduijie.pojo.dto.CheckResultDto;
import com.bright.hxj.cwduijie.pojo.dto.DuijieDataKeysDto;
import com.bright.hxj.cwduijie.pojo.dto.VoucherDto;
import com.bright.hxj.cwduijie.pojo.po.AccCode;
import com.bright.hxj.cwduijie.pojo.query.DuijieQuery;
import com.bright.hxj.cwduijie.pojo.vo.VoucherVO;
import com.bright.hxj.cwduijie.repository.VoucherRepository;
import com.bright.hxj.cwduijie.service.AbstractMonthlyReportApiService;
import com.bright.hxj.cwduijie.util.CommonUtil;
import com.bright.hxj.cwduijie.util.EntityManagerUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Component;

import java.time.YearMonth;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author hxj
 * @Date 2024/8/2 13:08
 * @Description 凭证冲洗接口 注意这不是常规接口 是处理特殊业务
 */

@Component
@RequiredArgsConstructor
@Slf4j
public class ApiFlushVoucherServiceImpl extends AbstractMonthlyReportApiService<VoucherDto, VoucherVO> {

    private final VoucherRepository voucherRepository;
    private final VoucherConverter voucherConverter;

    @Override
    public JpaSpecificationExecutor getJpaSpecificationExecutor() {
        return voucherRepository;
    }

    @Override
    public DataApi getDataApi() {
        return DataApi.VOUCHER;
    }

    @Override
    public Function<VoucherDto, Integer> getIdFunc() {
        return VoucherDto::getId;
    }

    @Override
    public Function<ApiDataCollection, Map<String, List<VoucherDto>>> getDataFunc() {
        return null;
    }

    @Override
    public Function<VoucherDto, VoucherVO> getConverterFunc() {
        return voucherConverter::dtoConvertVO;
    }

    @Override
    public boolean isExistsTYSHXYDMField() {
        return false;
    }

    @Override
    protected void getData(ApiDataCollection apiDataCollection, DuijieQuery duijieQuery) {
        // 获取需要重推的数据的DATA_KEY
        String ztDataKey = duijieQuery.getZtDataKey();
        String kjqj = CommonUtil.getSelectedYearMonth(duijieQuery.getDuijieYears(), duijieQuery.getDuijieMonths());
        // 通过DUIJIE_DATA_KEYS表获取推过的dataKey
        String dataKeyPrefix = ztDataKey + "-" + kjqj;
        List<DuijieDataKeysDto> duijieDataKeysDtos = duijieManager.getDuijieDataKeysLike(DataApi.VOUCHER.getServiceCode(), dataKeyPrefix);
        if (duijieDataKeysDtos.size() == 0) {
            log.debug("DUIJIE_DATA_KEY找不到历史推送凭证记录！" + ztDataKey + " " + kjqj);
        }

        List<String> dataKeys = duijieDataKeysDtos.stream().map(DuijieDataKeysDto::getDataKey)
                .distinct().collect(Collectors.toList());
        // 换成取凭证中间表DJ_PZM？
//        Map<String, Object> params = new HashMap<>(2);
//        params.put("ztDataKey", ztDataKey);
//        params.put("kjqj", kjqj);
//        List<Map<String, Object>> maps = EntityManagerUtil.queryForMapList(entityManager, "select data_key as DATA_KEY from DJ_PZM where ZT_DATA_KEY=:ztDataKey and kjqj=:kjqj and isnull(opType,1)=1 order by data_key", params);
//        List<String> dataKeys = ListUtil.toSingleList(maps, map -> (String) map.get("DATA_KEY"));

        apiDataCollection.setFlushVoucherDataKeys(dataKeys);
    }

    @Override
    protected void checkDataValid(Map<String, CheckResultDto> checkResultDtoMap, ApiDataCollection apiDataCollection) {
        // 不用检查数据 直接传指定模板的数据
    }

    @Override
    public void sendData(ApiDataCollection apiDataCollection, DuijieQuery duijieQuery, String batchId) throws JsonProcessingException {

        List<String> duijieDataKeysDtos = apiDataCollection.getFlushVoucherDataKeys();
        if (duijieDataKeysDtos.size() > 0) {
            String ztDataKey = duijieQuery.getZtDataKey();
            String kjqj = CommonUtil.getSelectedYearMonth(duijieQuery.getDuijieYears(), duijieQuery.getDuijieMonths());
            pushDefaultVoucherEntry(ztDataKey, kjqj, duijieDataKeysDtos);
        }
    }

    public void pushDefaultVoucherEntry(String ztDataKey, String kjqj, List<String> dataKeys) throws JsonProcessingException {
        String template = "{  \"DATA_KEY\": \"${DATA_KEY}\",  \"ZT_DATA_KEY\": \"${ZT_DATA_KEY}\",  \"BCXPZ_DATA_KEY\": \"\",  \"KJQJ\": \"${KJQJ}\",  \"LY\": 2,  \"LY_REMARK\": \"\",  \"ZDR\": \"-                      \",  \"PZRQ\": \"${PZRQ}\",  \"FJS\": 0,  \"SHR\": \"-                          \",  \"ZT\": 50,  \"LX\": 10,  \"PZXH\": ${XH},  \"JZR\": \"-                      \",  \"THYY\": \"\",  \"KJPZ_KJKM_LIST\": [{   \"DATA_KEY\": \"${DATA_KEY}\",   \"ZT_DATA_KEY\": \"${ZT_DATA_KEY}\",   \"DF_JE\": \"\",   \"ZY\": \"提现金\",   \"KJKM_BM\": \"${JFKM_BM}\",   \"JF_JE\": \"800.00\"  }, {   \"DATA_KEY\": \"${DATA_KEY}\",   \"ZT_DATA_KEY\": \"${ZT_DATA_KEY}\",   \"DF_JE\": \"800.00\",   \"ZY\": \"提现金\",   \"KJKM_BM\": \"${DFKM_BM}\",   \"JF_JE\": \"\"  }] }";
        List<Map<String, Object>> maps = new ArrayList<>();
        // v1.6.15 凭证日期跟会计期间走
        YearMonth kjqjYearMonth = CommonUtil.getYearMonthFromKJQJString(kjqj);
        String pzrq = kjqjYearMonth.getYear() + "-" + (kjqjYearMonth.getMonthValue() >= 10 ? kjqjYearMonth.getMonthValue() : "0" + kjqjYearMonth.getMonthValue()) + "-01";

        // v1.7.1 分录科目要取到最底级
        // 借方科目 取101下的最底级
        String querySQL = "SELECT BM from DJ_KMCSHSJ with(nolock) where opType=1 and NF=:years and ZT_DATA_KEY=:ztDataKey and BM like :bm order by CJ desc";
        Map<String, Object> params = new HashMap<>(2);
        params.put("years", kjqjYearMonth.getYear());
        params.put("ztDataKey", ztDataKey);
        params.put("bm", "101%");
        List<AccCode> accCodes = EntityManagerUtil.queryForClass(entityManager, querySQL, params, AccCode.class);
        String jfkm_bm = accCodes.size() > 0 ? accCodes.get(0).getBM() : "101";
        // 贷方科目 取401下的最底级
        params.put("bm", "401%");
        accCodes = EntityManagerUtil.queryForClass(entityManager, querySQL, params, AccCode.class);
        String dfkm_bm = accCodes.size() > 0 ? accCodes.get(0).getBM() : "401";

        for (String historyDataKey : dataKeys) {
            String content = StringUtil.replace(template, "${DATA_KEY}", historyDataKey);
            String xh = StringUtil.substringAfterLast(historyDataKey, "-");
            content = StringUtil.replace(content, "${ZT_DATA_KEY}", ztDataKey);
            content = StringUtil.replace(content, "${KJQJ}", kjqj);
            content = StringUtil.replace(content, "${XH}", xh);
            content = StringUtil.replace(content, "${PZRQ}", pzrq);
            // 借方、贷方科目编码
            content = StringUtil.replace(content, "${JFKM_BM}", jfkm_bm);
            content = StringUtil.replace(content, "${DFKM_BM}", dfkm_bm);

            Map map = objectMapper.readValue(content, Map.class);
            maps.add(map);
        }

        sendObjectData(maps, DataApi.VOUCHER, Collections.emptyList(), ztDataKey, null);
    }

    //    @Override
//    public DataApi getDeleteDataApi() {
//        return null;
//    }

//    @Override
//    public void sendDeleteData(DuijieQuery duijieQuery, String batchId) throws JsonProcessingException {
//        sendNeedDeleteData(batchId, getNeedDeleteData(duijieQuery), getDeleteDataApi(), getDataKeyFunc(), getIdFunc(), duijieQuery.getAccSet());
//    }

    @Override
    public String getCheckDuplicateGroupByFields() {
        return "DATA_KEY";
    }

    @Override
    public String getYearMonthColumnName() {
        return "KJQJ";
    }
}
